﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DataContexts.Supplier;

public partial class Admin_addEditRegion : System.Web.UI.Page
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    public int RegionId
    {
        get
        {
            return Helper.QSIntValue("id");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.AdminRegionAddEdit;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        if (!Page.IsPostBack)
        {
            LoadCountryDropDown();

            if (RegionId > 0)
            {
                Region region = supplierContext.Regions.SingleOrDefault(obj => obj.RegionId == RegionId);
                //CONTROL ASSIGNMENT
                txtRegionName.Text = region.RegionName;                
                ddlCountry.SelectedValue = region.CountryId.Value.ToString();                
            }
        }
    }

    private void LoadCountryDropDown()
    {
        ddlCountry.DataSource = from c in supplierContext.Countries
                               select c;
        ddlCountry.DataTextField = "CountryName";
        ddlCountry.DataValueField = "CountryId";
        ddlCountry.DataBind();

        ddlCountry.Items.Insert(0, new ListItem("--Select Country--", "0"));
    }

    protected void cvCountry_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (ddlCountry.SelectedIndex == 0)
        {
            args.IsValid = false;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Region region= new Region();
            if (RegionId > 0)
                region= supplierContext.Regions.SingleOrDefault(obj => obj.RegionId== RegionId);

            //PROPERTY ASSIGNMENT
            region.RegionName= txtRegionName.Text;
            region.CountryId= Convert.ToInt32(ddlCountry.SelectedValue);
            
            if (RegionId== 0)
                supplierContext.Regions.InsertOnSubmit(region);

            supplierContext.SubmitChanges();

            Response.Redirect("ViewRegions.aspx");
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewRegions.aspx");
    }
}
